﻿using Grpc.Core;
using Grpc.Net.Client;
using MP_Game.Protos.V1;
using MP_Game.Services.V1;
using MP_Network;

namespace MP_Server
{
    public class ForwardSvc : GatewayService.GatewayServiceBase
    {
        private static readonly GrpcChannel _verifyChannel =
            GrpcChannel.ForAddress(NetConst.GetIPAddress(NetConst.IPHost, NetConst.VerifyServerGrpcPort));
        private static readonly VerifyService.VerifyServiceClient _verifyClient = new VerifyService.VerifyServiceClient(_verifyChannel);
        public override async Task<GamePacket> ForwardPacket(GamePacket request, ServerCallContext context)
        {
            LogMsg.Warn("ForwardPkt被调用！");
            GamePacket packet;
            try
            {
                switch (request.CmdId)
                {
                    case CmdId.CmdLoginReq:
                        LogMsg.Warn("返回给玩家！");
                        packet = await _verifyClient.ProcessLoginAsync(request);
                        SendToPlayer(packet);// 转发给玩家
                        break;
                    default:
                        packet = request;
                        break;
                }
            }
            catch (Exception ex)
            {
                LogMsg.Warn($"ForwardSvc::ForwardPacket失败：{ex.Message}");
                packet = request;
            }
            return packet;
        }

        private void SendToPlayer(GamePacket packet)
        {
            int sessionId = packet.SessionId;
            Session? des = SessionMgr.Instance.GetSession(sessionId);
            if (des != null)
            {
                des.Send(packet);
            }
            else
            {
                LogMsg.Warn($"ForwardCtrl::OnServerCommand::对外转发时{des}未连接！");
            }
        }
    }
}
